package com.shiro.demo.Controller;

import com.shiro.demo.Model.User;
import com.sun.org.apache.xpath.internal.operations.Mod;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * @author Csea
 * @title
 * @date 2019/5/7 13:31
 */
@Controller
@Slf4j
public class TestController {
    @RequestMapping("/login")
    public ModelAndView login() {
        return new ModelAndView("login");
    }


    @RequestMapping("/index")
    public ModelAndView index() {
        return new ModelAndView("index");
    }

    @RequestMapping("/logout")
    public ModelAndView logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return new ModelAndView("login");
    }

    @RequestMapping("/admin")
    @ResponseBody
    public ModelAndView admin() {
        return new ModelAndView("adminSuccess");
    }

    @RequestMapping("/edit")
    @ResponseBody
    public ModelAndView edit() {
        return new ModelAndView("edit");
    }

    @RequestMapping("/unauthorized")
    public ModelAndView unauthorized() {
        return new ModelAndView("/unauthorized");
    }

    @RequestMapping("/loginUser")
    public ModelAndView loginUser(@RequestParam("username") String username, @RequestParam("password") String password,
                                  HttpSession session) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        log.info("【当前的账号密码输出是】" + username + " " + password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            User user = (User) subject.getPreviousPrincipals();
            session.setAttribute("user", user);
            return new ModelAndView("index");
        } catch (Exception e) {
            return new ModelAndView("login");
        }

    }
}
